/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.GroupMembershipNotification;
import edu.cmu.fithub.db.bean.User;

public class SearchInviteMemberAction extends Action {

	public SearchInviteMemberAction() {
	}

	public String getName() {
		return "searchInviteMember.do";
	}

	public String perform(HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("user");
		String searchUser = request.getParameter("search_person");
		String groupId = request.getParameter("groupId");
		request.setAttribute("groupId", groupId);
		Session dbSession = DBHelper.getSessionFactory().openSession();
		List<User> list = dbSession.createCriteria(User.class)
				.add(Restrictions.ilike("username", "%" + searchUser + "%"))
				.add(Restrictions.ne("userId", user.getUserId())).list();
		List<GroupMembershipNotification> groupNotificationList = dbSession
				.createCriteria(GroupMembershipNotification.class)
				.add(Restrictions.eq("group.groupId", Integer.parseInt(groupId)))
				.list();
		
		// remove users from search list whom invites were already sent
		List<Integer> userIdList = new ArrayList<Integer>();
		for(int i=0; i<groupNotificationList.size(); i++) {
			userIdList.add(groupNotificationList.get(i).getUserId());
		}
		
		for(int i=0; i<list.size(); i++) {
			if(userIdList.contains(list.get(i).getUserId())) {
				list.remove(i);
			}
		}

		User[] userList = new User[list.size()];
		userList = (User[]) list.toArray(userList);
		request.setAttribute("userList", userList);

		return "invite.jsp";
	}
}
